﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace MyUtils
{
    public delegate void CEventListenerDelegate(CBaseEvent evt);

    public class CEventDispatcher : Singleton<CEventDispatcher>
    {

        public override bool Init()
        {
            return true;
        }

        //创建一个哈希表用于存放添加的监听
        private Hashtable listeners = new Hashtable();


        /// <summary>
        /// 添加监听
        /// </summary>
        /// <param name="eventType">事件类型</param>
        /// <param name="listener">监听（委托类型）</param>
        public void AddEventListener(CEventType eventType, CEventListenerDelegate listener)
        {
            //添加监听
            listeners.Add(eventType, listener);


            /*
            //直接将事件类型赋值给表，然后得到他的值
            CEventListenerDelegate ceventListenerDelegate = this.listeners[eventType] as CEventListenerDelegate;


            //把监听添加到委托当中
            ceventListenerDelegate = (CEventListenerDelegate)Delegate.Combine(ceventListenerDelegate, listener);

            //事件（委托）重新赋值给键为eventType的监听
            this.listeners[eventType] = ceventListenerDelegate;
            */
        }

        /// <summary>
        /// 移除监听
        /// </summary>
        /// <param name="eventType"></param>
        /// <param name="listener"></param>
        public void RemoveEventListener(CEventType eventType, CEventListenerDelegate listener)
        {
            /*
            CEventListenerDelegate ceventListenerDelegate = this.listeners[eventType] as CEventListenerDelegate;
            if (ceventListenerDelegate!=null)
            {
                //如果事件（委托存在），则将里面的监听移除
                ceventListenerDelegate = (CEventListenerDelegate)Delegate.Remove(ceventListenerDelegate, listener);
            }
            this.listeners[eventType] = ceventListenerDelegate;
            */

            //移除监听
            listeners.Remove(eventType);
        }

        /// <summary>
        /// 分发事件消息
        /// </summary>
        /// <param name="evt">事件类型</param>
        public void DispatchEvent(CBaseEvent evt)
        {
            //从哈希表里得到事件监听
            CEventListenerDelegate ceventListenerDelegate = this.listeners[evt.Type] as CEventListenerDelegate;

            if (ceventListenerDelegate != null)
            {
                try
                {
                    //如果事件监听不为null，则将参数：事件类型 赋值给委托，由此触发事件函数
                    ceventListenerDelegate(evt);
                }
                catch
                {

                }
            }
        }

        public void RemoveAll()
        {
            this.listeners.Clear();
        }
    }
}
